import json

FILE = 'utils/list'
URL_MATCH_PATTERN = r'"*://*.%s/*"'
MANIFEST_TEMPLATE = 'utils/manifest.json.template'
MANIFEST_FILE = 'direninternet/manifest.json'
JS_FILE_TEMPLATE = 'utils/list.js.template'
JS_FILE = 'direninternet/script/list.js'
pattern = "##MACHERS##"

def readlist():
  f = open(FILE)
  lines = [line for line in f.readlines() if len(line.split("|")) >= 3]
  f.close()
  return lines

def get_matches(lines):
  urls = []
  urlmatches = ''
  for line in lines:
    tokens = line.split("|")
    name = tokens[0]
    reason = tokens[1]
    url = tokens[2].strip()
    if url:
      urls.append(url)

  return (",\n%s" % (" "*19)).join([URL_MATCH_PATTERN % url for url in urls])

def generate_manifest(matchers):
  f = open(MANIFEST_TEMPLATE)
  content = f.read()
  return content.replace(pattern, matchers)
  
def write_json_list(lines):
  block_list = {}
  for line in lines:
    tokens = line.split("|")
    name = tokens[0] 
    reason = tokens[1]
    url = tokens[2].strip()
    if name and reason and url:
        block_list[url] = {'name': name, 'reason': reason}
  
  content = json.dumps(block_list)
  f = open(JS_FILE_TEMPLATE)
  template = f.read()
  f.close()
  
  content = template.replace(pattern, content)
  
  f = open(JS_FILE, 'w')
  f.write(content)
  f.close()

def write_manifest(content):
  f = open(MANIFEST_FILE, 'w')
  f.write(content)
  f.close()

def main():
   lines = readlist()
   matches = get_matches(lines)
   content = generate_manifest(matches)
   write_json_list(lines)
   write_manifest(content)

if __name__ == "__main__":
    main()
    
  
